/**
 * 
 */
package com.conn.service.socket;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import com.conn.service.GlobalService;
import com.conn.service.socket.req.ClientRequest;
import com.conn.service.socket.req.TestRequest;
import com.conn.service.socket.req.zjh.ActionRequest;
import com.conn.service.socket.req.zjh.DeskRequest;
import com.conn.service.socket.resp.TestResponse;
import com.conn.service.socket.resp.zjh.ActionResponse;
import com.conn.service.socket.resp.zjh.DeskResponse;
import com.conn.service.socket.resp.zjh.SendResponse;
import com.conn.service.test.EnterRequest;
import com.conn.service.test.EnterResponse;
import com.macken.zjh.constant.Constants;

/**
 * @author lushouzhi
 * 
 */
public class MsgHandler extends IoHandlerAdapter implements GlobalService {
	public static int did = 1;
	public static int[] pids = new int[5];
	public static byte[] states = new byte[5];
	public static byte[] positions = new byte[5];
	public static int count = 0;
	public static IoSession[] sessions = new IoSession[5];
	public static byte deskState = Constants.DESK_STATE_READY;

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		super.exceptionCaught(session, cause);
		cause.printStackTrace();
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		ClientRequest request = (ClientRequest) message;

		if (request instanceof ActionRequest) {
			ActionRequest ar = (ActionRequest) request;
			switch (ar.action) {
			case Constants.ACTION_PREPARE:
				ActionResponse resp = new ActionResponse();
				for (int i = 0; i < pids.length; i++) {
					if (pids[i] == ar.pid) {
						states[i] = Constants.PLAYER_STATE_READY;
					}
				}
				notifyClient();

				// resp.pid = 200;
				// session.write(resp);
				break;
			default:
				break;
			}
		} else if (request instanceof DeskRequest) {
			DeskRequest rr = (DeskRequest) request;
			switch (rr.action) {
			case Constants.DESK_ENTER:
				addDesk(rr.pid, session);
				DeskResponse res = sendDeskData();
				session.write(res);
				notifyClient();
				notifySend();

				break;
			case Constants.DESK_EXIT:
				break;
			case Constants.DESK_CHANGE:
				break;
			default:
				break;
			}

		}

	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		System.out.println(System.currentTimeMillis() + "sessionClosed");
		for (int i = 0; i < sessions.length; i++) {
			if (session.equals(sessions[i])) {
				pids[i] = 0;
				states[i] = 0;
				positions[i] = 0;
				sessions[i] = null;
				count--;
				break;
			}
		}
		notifyClient();
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		super.sessionCreated(session);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		// if(session.getAttribute("")==null){
		// session.close(true);
		// }
	}

	public void addDesk(int pid, IoSession session) {
		for (int i = 0; i < pids.length; i++) {
			if (pids[i] == 0) {
				pids[i] = pid;
				states[i] = Constants.PLAYER_STATE_IDLE;
				positions[i] = (byte) (i + 1);
				sessions[i] = session;
				++count;
				break;
			}
		}
	}

	public SendResponse sendCard() {
		if (count == 3) {
			int count = 0;
			for (int i = 0; i < pids.length; i++) {
				if (states[i] == Constants.PLAYER_STATE_READY) {
					count++;
				}
			}
			int[] sendpids = new int[count];
			int j = 0;
			for (int i = 0; i < pids.length; i++) {
				if (states[i] == Constants.PLAYER_STATE_READY) {
					sendpids[j] = pids[i];
					j++;
				}
			}
			SendResponse sr = new SendResponse();
			sr.did = did;
			sr.count = count;
			sr.pids = sendpids;
			deskState = Constants.DESK_STATE_SEND;
			return sr;
		}
		return null;
	}

	public void notifySend() {

		SendResponse sr = sendCard();
		if (sr != null) {
			for (int i = 0; i < sessions.length; i++) {
				if (sessions[i] != null) {
					sessions[i].write(sr);
				}
			}
			deskState = Constants.DESK_STATE_DOING;
		}
	}

	public DeskResponse sendDeskData() {
		int[] spids = new int[count];
		byte[] sstates = new byte[count];
		byte[] spositions = new byte[count];
		int j = 0;
		for (int i = 0; i < pids.length; i++) {
			if (pids[i] != 0) {
				spids[j] = pids[i];
				sstates[j] = states[i];
				spositions[j] = positions[j];
				j++;
			}
		}
		DeskResponse response = new DeskResponse();
		response.did = did;
		response.state = deskState;
		response.count = count;
		response.pids = spids;
		response.states = sstates;
		response.positions = spositions;
		System.out.println("count:" + count);
		System.out.print("pids:");
		for (int i = 0; i < spids.length; i++) {
			System.out.print(spids[i] + " ");
		}
		System.out.println();
		System.out.print("pos:");
		for (int i = 0; i < spositions.length; i++) {
			System.out.print(spositions[i] + " ");
		}
		System.out.println();
		return response;
	}

	public void notifyClient() {
		DeskResponse res = sendDeskData();
		for (int i = 0; i < sessions.length; i++) {
			if (sessions[i] != null) {
				sessions[i].write(res);
			}
		}
	}

}
